import { Context } from 'egg';
import * as moment from 'moment';

function throws(errorCode: number, errorMsg: string) {
    throw { errorCode, errorMsg };
}

export default {
    success: (ctx: Context, res?: any, resMsg = '请求成功') => {
        ctx.body = {
            resCode: 0,
            data: res,
            resMsg,
        };
        ctx.status = 200;
    },

    fail: (ctx: Context, res?: any, status = 500, resCode = -999, resMsg = '系统内部错误') => {
        ctx.body = {
            resCode,
            data: res,
            resMsg,
        };
        ctx.status = status;
    },

    unauth: (msg = '未登录或者登陆实现') => {
        throws(-401, msg);
    },

    notFound: (msg = '请求不存在') => {
        throws(-404, msg);
    },

    innerError: (msg = '服务器内部错误') => {
        throws(-500, msg);
    },

    smsCodeError: (msg = '短信验证码错误或已过期' ) => {
        throws(-900, msg);
    },

    phoneBoundError: (msg = '手机号已经绑定') => {
        throws(-901, msg);
    },

    weixinBoundError: (msg = '微信号已经绑定') => {
        throws(-903, msg);
    },

    dbError: (msg = '数据库异常') => {
        throws(-902, msg);
    },

    invalidateParamsError: (msg = '异常参数') => {
        throws(-400, msg);
    },

    invalidateRole: (msg = '') => {
        throws(-402, msg);
    },

    generateToken: () => {
        return `${new Date().getTime()}${Math.floor(Math.random() * 9999)}`;
    },

    generateSmsCode: () => {
        const length = 6;
        const num = Math.floor(Math.random() * 999999);
        return (Array(length).join('0') + num).slice(-length);
    },

    now: () =>  moment().format('YYYY-MM-DD HH:mm:SS'),

    todayDate: () => moment().format('YYYY-MM-DD'),
    nowTime: () => moment().format('HH:mm:SS'),
};
